var searchVue;
var stopStock = stopStock || {};
var stockVue;
var stockGlobal = {};
stockGlobal.MiddleList = [];
stockGlobal.jiluliebiaonum = 0;
stockGlobal.timerAjax = 0; //设置定时器锁，用于处理刷新按钮多次请求接口
stockGlobal.timenum = 0;  //下拉接口异常后，清除填充的object
stockGlobal.scrollTimes = 0; //下拉刷新数据
stockGlobal.urlParam = 'slow'; // 默认tab，我的自选股
stockGlobal.orderBy = 'stockCode'; //接口参数，
stockGlobal.opList = 'getSelfStockList';
stockGlobal.pageTotal = 50;
stockGlobal.refreshnum = 0; //需要填充的条数
stockGlobal.page = 1;
stockGlobal.tabName = 'my';
stockGlobal.xuli = 'paixu';
stockGlobal.zhiBiao = 'moren';
stockGlobal.sortType = 'desc';  //正序
stockGlobal.direction = 'down'; //向下加载
stockGlobal.pageId = 'pdt_pms_269.gene';
stockGlobal.url_ver = {'url_ver':'SJCGBS-14521'};
stockGlobal.scrollToList = [];
stockGlobal.scrollHeight = 0;
stockGlobal.tabOne = 0;  //  用于切换tab下拉到底部埋点统计
stockGlobal.tabTwo = 0;
stockGlobal.scrollFalse = 0;  //下拉到最后一页，绑定下拉到底部埋点
stockGlobal.clickSortFlag = 0;  //用于点击表头排序ajax锁
stopStock = (function(){
	stopStock.initAjax = function(flag){
		$.ajax({
			type:'get',
			url:hxmConf.hxmAjaxUrl,
			data:{
				'op' : stockGlobal.opList,
				"orderBy" : stockGlobal.orderBy,
				"page" : stockGlobal.page,
				"sortType" : stockGlobal.sortType,
				"direction" : "down"
			},
			dataType:'json',
			cache:false,
			timeout:10000,
		})
		.fail(function(){
			if(flag == 'start'){
				$('.load-box').addClass('hide');
				$('.load-error').removeClass('hide');
				tabGlobal.coverErrorFlag = 2;
			}else{
				stockGlobal.scrollTimes = 0;
				stockGlobal.timenum = 1;
			}
		})
		.done(function(data){
			if(data.code == 0 && !$.isEmptyObject(data.data)){
				stockGlobal.page += 1;
				stockGlobal.urlData = data.data.newPage;
				if(flag == 'start' || flag == 'more' || flag == 'tab'){
					stockGlobal.pageTotal = data.data.stockNumber; //记录总数
					if(stockGlobal.pageTotal <= 50){
						stockGlobal.timenum = 1;
						stockGlobal.scrollFalse = 1; 
					}else{
						stockGlobal.timenum = 0;
						(50*(stockGlobal.page-1) >= stockGlobal.pageTotal) && (stockGlobal.scrollFalse = 1); 
						50*stockGlobal.page < stockGlobal.pageTotal ? (stockGlobal.refreshnum = 50) : (stockGlobal.refreshnum = stockGlobal.pageTotal - 50*(stockGlobal.page - 1));
					}
				}
				
				if(flag == 'tab'){
					stockVue.stockList = data.data.newPage;
					$(window).scrollTop(0);
				}

				if(flag == 'more'){
					var j=0;
					var length = stockVue.stockList.length;
					stockGlobal.scrollTimes = 0;
					for(var i=length-stockGlobal.jiluliebiaonum;i<length;i++,j++){
						Vue.set(stockVue.stockList,i,stockGlobal.urlData[j]);
					}
					//下拉加载，埋点统计
					hxmClickStat(stockGlobal.pageId+'.'+stockGlobal.tabName+'.load.'+(stockGlobal.page-2),stockGlobal.url_ver);
				}
				(flag == 'start') && (stopStock.setLimitStockVue());
			}
		})
	},
	stopStock.setLimitStockVue = function(){
		stockVue = new Vue({
			el:'.stockSearch',
			data:{
				stockData : stockGlobal.urlData,
				stockList:[],
				ajaxDataList:[],
				roseData:2,
				highData:2,
				codeData:2,
			},
			methods:{
				switchTabTitle:function(type){ //点击表头两个个板块
					stockGlobal.urlParam = type;
					stockGlobal.page = 1;
					stockGlobal.scrollFalse = 0;
					type == 'slow' ? (hxmClickStat(stockGlobal.pageId+'.my',stockGlobal.url_ver)) : (hxmClickStat(stockGlobal.pageId+'.all',stockGlobal.url_ver));
					type == 'slow' ? (stockGlobal.opList = 'getSelfStockList') : (stockGlobal.opList = 'getStockList');
					setTabTitle();
					stopStock.initAjax('tab');
				},
				clickTabSortStock:function(event){
					if(stockGlobal.clickSortFlag == 0){
						stockGlobal.clickSortFlag = 1;
						var obj = event.currentTarget;
						var id = $(obj).attr('flag-id');
						stockGlobal.page = 1; //点击排序时，将page重置为1
						switch (id) {  //  1  表示逆  0  表示正  2不变
							case "1":

								this.roseData = (++this.roseData)%3;
								InsBackground(obj,this.roseData);
								stockGlobal.zhiBiao = 'jiyin';
								this.roseData == 2 ? (stockGlobal.orderBy = 'stockCode') : (stockGlobal.orderBy = 'score');
								this.roseData == 0 ? (stockGlobal.sortType = 'desc') : (stockGlobal.sortType = 'asc');
								break;
							case "2":
								this.highData = (++this.highData)%3;
								InsBackground(obj,this.highData);
								stockGlobal.zhiBiao = 'jiage';
								this.highData == 2 ? (stockGlobal.orderBy = 'stockCode') : (stockGlobal.orderBy = 'price');
								this.highData == 0 ? (stockGlobal.sortType = 'desc') : (stockGlobal.sortType = 'asc');
								break;
							case "3":
								this.codeData = (++this.codeData)%3;
								InsBackground(obj,this.codeData);
								stockGlobal.zhiBiao = 'zhangfu';
								this.codeData == 2 ? (stockGlobal.orderBy = 'stockCode') : (stockGlobal.orderBy = 'change');
								this.codeData == 0 ? (stockGlobal.sortType = 'desc') : (stockGlobal.sortType = 'asc');
								break;		
						}
						stockGlobal.sortType == 'desc' ? (stockGlobal.xuli = 'desc') : (stockGlobal.xuli = 'asc');  //用于埋点统计
						//  默认排序埋点  和   点击正常排序埋点
						stockGlobal.orderBy == 'stockCode' ? (hxmClickStat(stockGlobal.pageId+'.'+stockGlobal.tabName+'.'+stockGlobal.zhiBiao+'.unsort')) : (hxmClickStat(stockGlobal.pageId+'.'+stockGlobal.tabName+'.'+stockGlobal.zhiBiao+'.'+stockGlobal.sortType,stockGlobal.url_ver));
						if(stockGlobal.orderBy == 'stockCode'){
							stockGlobal.zhiBiao = 'moren';
							stockGlobal.xuli = 'paixu';
						}
						$(window).scrollTop(0);
						this.getPageData();
					}
					
				},
				refreshData:function(){ //刷新按钮数据
					stockGlobal.scrollToList = [];
					stockGlobal.timenum = 1;
					stockGlobal.scrollHeight = $(window).scrollTop();
					hxmClickStat(stockGlobal.pageId+'.'+stockGlobal.tabName+'.refresh',stockGlobal.url_ver);
					WindowscrollAjax(1);
				},
				getPageData:function(flag){  //点击排序，获取排序数据
					$.ajax({
						type:'get',
						url:hxmConf.hxmAjaxUrl,
						dataType:'json',
						data:{
							'op' : stockGlobal.opList,
							"orderBy" : stockGlobal.orderBy,
							"page" : stockGlobal.page,
							"sortType" : stockGlobal.sortType,
							"direction" : "down"
						},
						cache:false,
						timeout:10000,
					})
					.done(function(data){
						if(data.code == 0 && !$.isEmptyObject(data.data)){
							stockGlobal.clickSortFlag = 0;
							stockGlobal.page += 1;
							stockGlobal.urlData = data.data.newPage;
							stockVue.stockList = stockGlobal.urlData;
							setTabTitle();
						}
					})
					.fail(function(){
						stockGlobal.clickSortFlag = 0;
						stockGlobal.timerAjax = 0;
						stockGlobal.timenum++;
					})
				},
				cancelEvent:function(){  //点击输入框取消按钮
					hxmClickStat(stockGlobal.pageId+'.search.cancel',stockGlobal.url_ver);
					$('.list_box_height').css({
						'position':'fixed',
						'height':'2.62rem'
					});
					$('.search-box div').css({
						'width':'100%'
					});
					$('.cancel_button').hide();
					$('.product-search').val('');
					$('.closeMsg').hide();
					$('.stockSearch .rise_title').show();
					$('.background').show();
					$('.datalist').hide();
					$('#cc_title').show();
					$('#listHeight').show();
					$('body').addClass('vueBoxBack');
					setTimeout(function(){
						$('.bottom_fixed_wrap').show();
					},200);
				},
				JumpToztDetailSearch:function(code,key,market){  //列表股票数据跳转涨停基因分时
					//设置本地存储
					setSessionSaveFunction();
					hxmJumpPageStat(stockGlobal.pageId+'.'+stockGlobal.tabName+'.'+stockGlobal.zhiBiao+'.'+stockGlobal.xuli+'.'+key,'pdt_pms_269_gene',{'url_ver':'SJCGBS-14521','targid':'stock_'+code,'to_frameid':'2804'});
					setTimeout(function(){
						window.location.href = 'oldztDetail.html?code='+code+'&marketId='+market;
					},300);
				}
			}
		});
		Vue.nextTick(function(){
			stockVue.stockList = stockGlobal.urlData;
			bindEvent();
			scrollBottomStat();
			if(localStorage.getItem('saveObj')){
				stockGlobal.timenum = 1;
				var sessionObj = localStorage.getItem('saveObj');
				sessionObj = JSON.parse(sessionObj);
				stockGlobal.page = sessionObj.page;
				stockGlobal.urlParam = sessionObj.urlParam;
				stockGlobal.tabName = sessionObj.tabName;
				stockGlobal.orderBy = sessionObj.orderBy;
				stockGlobal.sortType = sessionObj.sortType;
				stockGlobal.zhiBiao = sessionObj.zhiBiao;
				stockGlobal.xuli = sessionObj.xuli;
				stockGlobal.opList = sessionObj.opList;
				stockGlobal.scrollHeight = sessionObj.scrollHeight;
				setTabTitle();
				WindowscrollAjax(1);
				localStorage.removeItem('saveObj');
			}else{
				$('.load-box').addClass('hide');
				setTabTitle();
			}
			//设置表头排序图标 
			switch(stockGlobal.orderBy){
				case 'price':
					stockGlobal.sortType == 'desc' ? ($('#cc_title .high>span>ins:last-child').addClass('bottomup')) : ($('#cc_title .high>span>ins:first-child').addClass('topup'));
					break;
				case 'change':
					stockGlobal.sortType == 'desc' ? ($('#cc_title .code>span>ins:last-child').addClass('bottomup')) : ($('#cc_title .code>span>ins:first-child').addClass('topup'));
					break;
				case 'score':
					stockGlobal.sortType == 'desc' ? ($('#cc_title .rose>span>ins:last-child').addClass('bottomup')) : ($('#cc_title .rose>span>ins:first-child').addClass('topup'));
					break;
				case 'stockCode':
					$('#cc_title li span ins').removeClass('topup');
					$('#cc_title li span ins').removeClass('topdown');
					$('#cc_title li span ins').removeClass('bottomup');
					$('#cc_title li span ins').removeClass('bottomdown');
					break;				
			}
		});

	}

	return {
		initAjax : stopStock.initAjax,
		setLimitStockVue : stopStock.setLimitStockVue
	} 
})();

//点击刷新按钮后，刷新历史数据,回调函数，处理顺序排序
function WindowscrollAjax(j){
	$.ajax({
		type:'get',
		url:hxmConf.hxmAjaxUrl,
		dataType:'json',
		data:{
			'op' : stockGlobal.opList,
			"orderBy" : stockGlobal.orderBy,
			"page" : j,
			"sortType" : stockGlobal.sortType,
			"direction" : "down"
		},
		cache:false,
		timeout:10000,
	})
	.done(function(data){
		if(data.code == 0 && !$.isEmptyObject(data.data)){
			$('.load-box').addClass('hide');
			var length = data.data.newPage.length;
			for(var i = 0;i<length;i++){
				stockGlobal.scrollToList.push(data.data.newPage[i]);
			}
			stockVue.stockList = stockGlobal.scrollToList;
			stockGlobal.pageTotal = data.data.stockNumber; //记录总数
			if(j == stockGlobal.page-1){
				$(window).scrollTop(stockGlobal.scrollHeight);
				if(stockGlobal.pageTotal <= 50){
					stockGlobal.timenum = 1;
					stockGlobal.scrollFalse = 1; 
				}else{
					stockGlobal.timenum = 0;
					(50*(stockGlobal.page-1) >= stockGlobal.pageTotal) && (stockGlobal.scrollFalse = 1);  
					50*stockGlobal.page < stockGlobal.pageTotal ? (stockGlobal.refreshnum = 50) : (stockGlobal.refreshnum = stockGlobal.pageTotal - 50*(stockGlobal.page - 1));
				}
			}
			if(j<stockGlobal.page-1){
				WindowscrollAjax(++j);
			}
		}
	})
	.fail(function(){
		stockGlobal.timenum = 0;
		$('.load-box').addClass('hide');
		$('.load-error').removeClass('hide'); 
	})
}



function setTabTitle(){
	$('.rise_title>div span').hide();
	switch (stockGlobal.urlParam){
		case 'slow': //缓慢涨停
			stockGlobal.tabName = 'my';
			$('.rise_title>div:nth-child(1) span').show();
			break;
		case 'word': //一字板
			stockGlobal.tabName = 'all';
			$('.rise_title>div:nth-child(2) span').show();
			break;
	}

}


function InsBackground(obj,num){
	$(obj).parent().find('ins').removeClass('topup');
	$(obj).parent().find('ins').removeClass('topdown');
	$(obj).parent().find('ins').removeClass('bottomup');
	$(obj).parent().find('ins').removeClass('bottomdown');
	(num != 2) && (num == 1 ? ($(obj).find('ins:first').addClass('topup')) : ($(obj).find('ins:last').addClass('bottomup')));
}

//搜索股票，点击跳转基因详情页
function JumpToProductPage(code,num,id){
	setSessionSaveFunction();
	hxmJumpPageStat(stockGlobal.pageId+'.search.res.'+(num+1),'pdt_pms_269_gene',{'url_ver':'SJCGBS-14521','targid':'stock_'+code,'to_frameid':'2804'});
	//解决android部分机型软键盘不能自动收起的问题
	setTimeout(function(){
		window.location.href = "oldztDetail.html?code="+code+'&marketId='+id;
	},500);
}



// 滑动到底部埋点
function scrollBottomStat(){
    $(window).on('scroll', function(){
        var dpr = $('html').data('dpr') ? $('html').data('dpr') : 1; // 页面dpr
        var windowHeight = getPlatform() == 'iphone' ? window.screen.height : $(window).height();//分辨率的高度
        var scrollHeight = $(window).scrollTop() / dpr;//document.documentElement.scrollTop;//滚动的高度
        var totalHeight = $(document).height() / dpr;//文档的总高度
        if((scrollHeight) >= (totalHeight - windowHeight)){
            if(stockGlobal.tabName == 'my'){
            	if(stockGlobal.tabOne == 0 && stockGlobal.scrollFalse == 1){
            		stockGlobal.tabOne = 1;
            		hxmClickStat(stockGlobal.pageId+'.my.bottom',stockGlobal.url_ver);
            	}
            }else{
            	if(stockGlobal.tabTwo == 0 && stockGlobal.scrollFalse == 1){
            		stockGlobal.tabTwo = 1;
            		hxmClickStat(stockGlobal.pageId+'.all.bottom',stockGlobal.url_ver);
            	}
            }
        }
    });
}


//监听搜索框内容变化
function propertychange(text){
	$.ajax({
		type:'get',
        url:hxmConf.hxmAjaxUrl,
        dataType:'json',
        data:{
        	"op":"searchStock",
        	'pattern':text,
        },
        cache:false,
        timeout:10000,
	})
	.done(function(data){
		if(data.code == 0 && !$.isEmptyObject(data.data)){
			var html = '';
			$(document).off('click','.datalist ul li');
			$('.datalist ul li').remove();
			$('.datalist ul p').remove();
			$('.no-product').hide();
			$('.datalist').show();
			$.each(data.data,function(key,value){
				html += '<li data-code='+value.stockCode+' data-id='+value.marketId+'><span>'+value.stockName+'</span><span>'+value.stockCode+'</span></li>';
			});
			html += '<p>因风险控制及合规要求，本功能暂不支持ST股票的涨停基因计算，敬请谅解！</p>';
			$('.datalist ul').append(html);
			$(document).on('click','.datalist ul li',function(){
				JumpToProductPage($(this).data('code'),$(this).index(),$(this).data('id'));
			});
			//处理股票输入框中的数据和列表不一致问题
			var textMsg = $.trim($('.product-search').val());
			if(text != textMsg){
				propertychange(textMsg);
			}

		}else{
			$('.no-product').show();
			$('.datalist').hide();
		}
	})
}



function bindEvent(){
	$('.no-product').hide();
	
	$('.product-search').on('focus',function(){
		$('.datalist ul p').remove();
		var html = '<p>因风险控制及合规要求，本功能暂不支持ST股票的涨停基因计算，敬请谅解！</p>';
		$('.datalist ul').append(html);
		$('.datalist ul li').remove();
		$('.cancel_button').show();
		$('.no-product').hide();
		$('.datalist').show();
		$('.search-box div').css({
			'width':'5.52rem'
		});
		hxmClickStat(stockGlobal.pageId+'.search',stockGlobal.url_ver);
		$('.list_box_height').css({
			'position':'relative',
			'height':'0.88rem'
		});
		$('.stockSearch .rise_title').hide();
		$('.background').hide();
		$('#cc_title').hide();
		$('#listHeight').hide();
		$('body').removeClass('vueBoxBack');
		$('.bottom_fixed_wrap').hide();

	});

	$('.closeMsg').on('click',function(){
		$('.product-search').val('');
		$('.datalist ul li').remove();
		$('.closeMsg').hide();
	});

	$('.product-search').on('input propertychange',function(){
		var text = $(this).val();
		if($.trim(text)){
			$(this).css('color','#323232');
			$('.closeMsg').show();
			try{
				propertychange(text);
			}catch(e){
				console.log(e);
			}
		}else{
			$(this).css('color','#999');
			$('.closeMsg').hide();
			$('.datalist ul li').remove();
		}
	});

	$(window).on('touchmove scroll',function(){

		if($(window).scrollTop() + $(window).height() >= $('#listHeight').height() && $(document).height() > $(window).height()){
			if(stockGlobal.scrollTimes == 0 && stockGlobal.timenum == 0 && stockGlobal.scrollFalse == 0){
				for(var i=0;i<stockGlobal.refreshnum;i++){
				var object = {
					"stockName":"--",
					"stockCode":"--",
					"score":"--",
					"price":"--",
					"change":"--"
				};
				stockVue.stockList.push(object);  //下拉加载，符合条件后，先给默认值填充
			}
				stockGlobal.scrollTimes = 1;
				stockGlobal.jiluliebiaonum = stockGlobal.refreshnum; 
				stopStock.initAjax('more');
			}
		}
	});
}



//本地存储用户记录
function setSessionSaveFunction(){
	var obj = {
		'page':stockGlobal.page,
		'orderBy':stockGlobal.orderBy,
		'opList':stockGlobal.opList,
		'sortType':stockGlobal.sortType,
		'urlParam':stockGlobal.urlParam,
		'tabName':stockGlobal.tabName,
		'zhiBiao':stockGlobal.zhiBiao,
		'xuli':stockGlobal.xuli,
		'scrollHeight':$(window).scrollTop()
	}
	obj = JSON.stringify(obj);
	localStorage.setItem('saveObj',obj);
}